package org.vy.dal;

import org.vy.dal.common.DBSeqPrefix;
import org.vy.dal.common.DBSeqTable;

public abstract class CommonSeqProvider<T> {
	
	@SuppressWarnings("unchecked")
	public synchronized T getNextSequence(){
		Object seq = null;
		try{
			DBSeqTable anno = getClass().getAnnotation(DBSeqTable.class);
			DBSeqPrefix prefix = getClass().getAnnotation(DBSeqPrefix.class);
			if(prefix != null){
				seq = getNextPrefixedSequence(anno, prefix);
			}else if(anno != null) {
				seq = getNextLongSequence(anno);
			}
		}catch(Exception e){
			//TODO
			e.printStackTrace();
		}
		return (T)seq;
	}
	
	protected synchronized String getNextLongSequence(DBSeqTable anno){
		String seq = null;
		try{
			if(anno != null) {
				String sql = "SELECT SEQUENCE FROM "+ anno.value() + "_SEQ";
				seq = QueryManager.getSequence(sql);
				sql = "UPDATE "+ anno.value() +"_SEQ SET SEQUENCE=SEQUENCE+1";
				QueryManager.updateSequence(sql);
			}
		}catch(Exception e){
			//TODO
			e.printStackTrace();
		}
		return seq;
	}
	
	protected String getNextPrefixedSequence(DBSeqTable anno, DBSeqPrefix prefix){
		String seq = null;
		try{
			if(anno != null) {
				seq = getNextLongSequence(anno);
				if(prefix != null) {
					seq = prefix.value() + seq;
				}
			}
			return seq;
		}catch(Exception e){
			//TODO
			e.printStackTrace();
		}
		return null;
	}

}
